package com.iary.interfaces.web.admin.block;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.iary.domain.model.block.Block;
import com.iary.domain.model.block.BlockDesc;
import com.iary.domain.model.block.BlockType;
import com.iary.domain.service.BlockService;

@Controller
@RequestMapping("/admin/")
public class BlockAdminController {

	@Autowired
	private BlockService blockService;
	
	@Autowired
	private BlockCommandValidator validator;

	@RequestMapping("block")
	public ModelAndView execute(@RequestParam() String type) {
		BlockType blockType = BlockType.valueOf(type);
		if (blockType == null) {
			return null;
		}
		List<Block> result = blockService.getBlocksByType(blockType);
		ModelAndView mav = new ModelAndView("admin/block-mgmt");
		mav.addObject("result", result);
		return mav;
	}

	@RequestMapping(value = "/block/new", method = RequestMethod.POST)
	public ModelAndView create(@ModelAttribute("command") BlockCommand command, BindingResult errors) {
		validator.validate(command, errors);
		if(!errors.hasErrors()){
			BlockDesc blockDesc = new BlockDesc(BlockType.valueOf(command.getType()));
			blockDesc.setOrder(Integer.valueOf(command.getOrder()));
			blockDesc.setValue(command.getValue());
			blockService.save(new Block(blockDesc));
			return new ModelAndView("redirect:/admin/block?type=" + command.getType());
		}
		
		List<Block> result = blockService.getBlocksByType(BlockType.valueOf(command.getType()));
		ModelAndView mav = new ModelAndView("admin/block-mgmt");
		mav.addObject("result", result);
		return mav;
	}

	@RequestMapping(value = "/block/edit", method = RequestMethod.POST)
	public String update(@ModelAttribute("blockDesc") BlockDesc blockDesc,
			@RequestParam() Long id) {
		blockService.update(id, blockDesc);
		return "redirect:/admin/block?type=" + blockDesc.getType();
	}

}
